package com.obas.monitor.codec;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.obas.business.common.vo.AtMessage;

import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Output;

public class MessageResponseEncoder implements ProtocolEncoder {

   @Override
   public void dispose(IoSession session) throws Exception {
      // TODO Auto-generated method stub

   }

   @Override
   public void encode(IoSession session, Object message, ProtocolEncoderOutput out)
         throws Exception {
      AtMessage atMsg = (AtMessage) message;
      byte[] bytes = getBytes(atMsg.getParam());
      int capacity = 8 + getBytes(atMsg.getParam()).length;
      IoBuffer buffer = IoBuffer.allocate(capacity + 4, false);
      buffer.setAutoExpand(true);
      buffer.putInt(capacity);
      buffer.putInt(atMsg.getId());
      buffer.putInt(atMsg.getCommand());
      buffer.put(bytes);
      buffer.flip();
      out.write(buffer);
   }
   
   private byte[] getBytes(Object param) throws IOException {
      Amf3Output amfOut = new Amf3Output(SerializationContext.getSerializationContext());
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      amfOut.setOutputStream(outStream);
      amfOut.writeObject(param);

      return outStream.toByteArray();
  }
}
